package cn.iclass.common.utils.oss;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;

import java.io.File;
import java.io.InputStream;

/**
 * @Description: 阿里云OSS工具
 * @Author: alan
 * @Date: 2019/6/11 9:24 AM
 */
@Slf4j
public class OSSUtils {


	private final static String BUCKET = "liantong-file";
	private final static String DOMAIN = "http://liantong-file.oss-cn-shenzhen.aliyuncs.com";
	private final static String ACCESS_KEY_ID = "LTAItwSZuPO1PNM8";
	private final static String ACCESS_KEY_SECRET = "7F8lG1gbdB3UcDIzYaNEFnynW8vpjQ";
	private static OSSUtils ourInstance = new OSSUtils();
	private static OSSClient client;
	/**
	 * 外网地址
	 */
	private String ENDPOINT = "oss-cn-shenzhen.aliyuncs.com";

	private OSSUtils() {
		init();
	}

	public static OSSUtils getInstance() {
		return ourInstance;
	}


	public static String upload(File file) {
		String fileFullName = file.getName();
		String key = FileTypeUtils.getPath(fileFullName);
		client.putObject(BUCKET, key, file);
		return String.format("%s/%s", DOMAIN, key);
	}

	public static String upload(InputStream is, String fileName) {
		String key = FileTypeUtils.getPath(fileName);
		client.putObject(BUCKET, key, is);
		return String.format("%s/%s", DOMAIN, key);
	}

	public static File download(String url) {
		String key = url.split(DOMAIN + "/")[1];
		File tmpFile = FileUtil.createTempFile(IdUtil.fastSimpleUUID(), FilenameUtils.getExtension(key),
				FileUtil.getTmpDir(), true);
		client.getObject(new GetObjectRequest(BUCKET, key), tmpFile);
		return tmpFile;
	}

	public static void main(String[] args) {
		File file = new File("f:/路飞.jpg");
        /*String url = "http://certfile.chain-pin.com/file/20190304/a053972a67f64bd7b395da2d9cdbb36d.xlsx";
        String key = url.split(DOMAIN)[1];*/
		System.out.println(upload(file));
	}

	private void init() {
		client = new OSSClient(ENDPOINT, ACCESS_KEY_ID,
				ACCESS_KEY_SECRET);
		log.info("阿里云oss连接地址为{}", ENDPOINT);

	}


}
